/*
 * @Author: zhangxuanjiu
 * @Date: 2017-08-10 14:38:36
 * @Last Modified by: zhangxuanjiu
 * @Last Modified time: 2017-08-11 09:18:25
 */

const gulp = require('gulp');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const config = require('./webpack.config.js');
const configDev = require('./webpack.config-dev.js');
const del = require('del');
const path = require('path');
const serverConfig = require('./serverConfig.js')

// 清空文件夹
gulp.task('clean', function() {
  return del([
    './build/*',
    './build/style/*',
    './build/lib/*',
    './build/img/*'
  ]);
});

// 复制
gulp.task('copy', ['clean'], function() {
  gulp.src(['./src/style/*.css'])
    .pipe(gulp.dest('./build/style/'))
  gulp.src(['./src/lib/*.js'])
    .pipe(gulp.dest('./build/lib/'))
  gulp.src(['./src/img/*'])
    .pipe(gulp.dest('./build/img/'))
  return gulp.src(['./src/*.html'])
    .pipe(gulp.dest('./build/'));
});

// 监听html/css文件改动
gulp.task('watch', function() {
  gulp.watch('./src/*.html', function(event) {
    gulp.src(['./src/*.html'])
      .pipe(gulp.dest('./build/'))
  });
  gulp.watch('./src/style/*.css', function(event) {
    gulp.src(['./src/style/*.css'])
      .pipe(gulp.dest('./build/style/'))
  });
});

gulp.task('dev', ['copy', 'watch'], function() {
  var compiler = webpack(configDev);
  var server = new WebpackDevServer(compiler, {
    hot: true,
    // enable HMR on the server

    contentBase: path.resolve(__dirname, 'build'),
    // match the output path

    publicPath: '/',
    // match the output `publicPath`

    stats: { colors: true },

    proxy: {},

    port: serverConfig.port

  });
  server.listen(serverConfig.port, serverConfig.host);
});

gulp.task('build', ['copy'], function() {
  webpack(config).run(function() {
    console.log('build finished!')
  });
});